package gframework.bean.table;

import java.awt.KeyboardFocusManager;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Vector;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableColumn;

public class GTable extends javax.swing.JTable {

    private boolean habilitaOrdenacao = false;
    private boolean showGridLine = false;
    private boolean multiSelect = false;

    public void carregar() {
    }

    public GTable() {
        initComponents();

        setShowGridLine(false);
        setMultiSelect(false);

        HashSet kTab = new HashSet(1);
        kTab.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));

        setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, kTab);

        HashSet kShiftTab = new HashSet(1);
        kShiftTab.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));

        setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, kShiftTab);

        this.setFocusable(false);
        this.getTableHeader().setReorderingAllowed(false);
    }

    @Override
    public void tableChanged(TableModelEvent e) {
        super.tableChanged(e);
        repaint();
    }

    public void setModel(Vector<Object[]> i_dados, GColumnTable[] i_colunas) throws Exception {
        Object[][] dadosNovo = new Object[i_dados.size()][i_colunas.length];

        int i = 0;

        for (Object[] dados : i_dados) {
            dadosNovo[i] = dados;
            i++;
        }

        setModel(dadosNovo, i_colunas);
    }

    public void setModel(Object[][] i_dados, GColumnTable[] i_colunas) throws Exception {
        Vector<Integer> vColunaEditavel = new Vector();
        Vector<Integer> vAlinhamento = new Vector();
        Vector<Object> vParser = new Vector();

        int linhaSelecionada = getSelectedRow();

        setAutoCreateColumnsFromModel(false);

        GTableModel model = new GTableModel();

        while (getColumnCount() > 0) {
            removeColumn(getColumnModel().getColumn(0));
        }

        for (int i = 0; i < i_colunas.length; i++) {
            GColumnTable oColumnTable = i_colunas[i];
            TableColumn oColuna = new TableColumn(i);

            if (oColumnTable.editavel) {
                vColunaEditavel.add(i);
            }

            vAlinhamento.add(oColumnTable.alinhamento);

            if (!(oColumnTable.parser instanceof DecimalFormat) && !(oColumnTable.parser instanceof SimpleDateFormat) && !(oColumnTable.parser == null)) {
                throw new Exception("Parser inválido!");
            }

            vParser.add(oColumnTable.parser);

            oColuna.setHeaderValue(oColumnTable.titulo);
            oColuna.setPreferredWidth(oColumnTable.tamanho);

            if (!oColumnTable.redimensionavel) {
                oColuna.setMaxWidth(oColumnTable.tamanho);
            }

            addColumn(oColuna);
            model.addColumn(oColumnTable.titulo);
        }

        for (int l = 0; l < i_dados.length; l++) {
            for (int c = 0; c < i_dados[l].length; c++) {
                Object dado = i_dados[l][c];

                if ((dado instanceof Integer) || (dado instanceof Long) || (dado instanceof Double) || (dado instanceof String)) {
                    if (i_colunas[c].alinhamento == SwingConstants.RIGHT) {
                        i_dados[l][c] = String.valueOf(dado) + " ";
                    } else {
                        i_dados[l][c] = " " + String.valueOf(dado);
                    }
                }
            }

            model.addRow(i_dados[l]);
        }

        GTableCellRenderer renderer = new GTableCellRenderer();
        renderer.setAlinhamento(vAlinhamento);

        this.setDefaultRenderer(Class.forName("java.lang.Object"), renderer);

        model.setColunasEditaveis(vColunaEditavel);
        model.setParser(vParser);

        this.setModel(model);

        if (i_dados.length > 0) {
            this.setFocusable(true);
        } else {
            this.setFocusable(false);
        }

        if (linhaSelecionada >= 0) {
            if (linhaSelecionada <= (getRowCount() - 1)) {
                setRowSelectionInterval(linhaSelecionada, linhaSelecionada);
            } else if (getRowCount() > 0) {
                setRowSelectionInterval(getRowCount() - 1, getRowCount() - 1);
            }
        }
    }

    public int getLinhaSelecionada() {
        if (this.getSelectedRow() >= 0) {
            return this.convertRowIndexToModel(this.getSelectedRow());
        } else {
            return -1;
        }
    }

    public void setLinhaSelecionada(int row) {
        this.setRowSelectionInterval(row, row);
    }

    public int getColunaSelecionada() {
        if (this.getSelectedColumn() >= 0) {
            return this.convertColumnIndexToModel(this.getSelectedColumn());
        } else {
            return -1;
        }
    }

    public void editaCampo(int row, int column) throws Exception {
        boolean toggle = true;
        boolean extend = true;

        changeSelection(row, column, toggle, extend);

        if (editCellAt(row, column)) {
            getEditorComponent().requestFocus();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popMenu = new javax.swing.JPopupMenu();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItem1 = new javax.swing.JMenuItem();

        popMenu.add(jSeparator1);

        jMenuItem1.setText("Mais...");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        popMenu.add(jMenuItem1);

        setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
    }// </editor-fold>//GEN-END:initComponents
    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            evt.consume();
        }
    }//GEN-LAST:event_formKeyPressed

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
        if (this.getRowCount() > 0) {
            int index = this.getSelectedRow();

            if (index == -1) {
                this.setRowSelectionInterval(0, 0);
            }
        }
    }//GEN-LAST:event_formFocusGained

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    public boolean isHabilitaOrdenacao() {
        return habilitaOrdenacao;
    }

    public void clear() throws Exception {
        GColumnTable[] colunas = new GColumnTable[]{};
        Object dados[][] = new Object[0][0];

        this.setModel(dados, colunas);
    }

    public void setHabilitaOrdenacao(boolean habilitaOrdenacao) {
        this.habilitaOrdenacao = habilitaOrdenacao;
        this.setAutoCreateRowSorter(true);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPopupMenu popMenu;
    // End of variables declaration//GEN-END:variables

    public boolean isShowGridLine() {
        return showGridLine;
    }

    public void setShowGridLine(boolean showGridLine) {
        this.showGridLine = showGridLine;

        /*if (!showGridLine) {
        setGridColor(UIManager.getColor("Table.background"));
        setBorder(BorderFactory.createLineBorder(UIManager.getColor("Table.background")));
        }*/
        this.setShowGrid(false);
    }

    public boolean isMultiSelect() {
        return multiSelect;
    }

    public void setMultiSelect(boolean multiSelect) {
        this.multiSelect = multiSelect;

        if (multiSelect) {
            this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        } else {
            this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        }
    }
}